package cn.oracle;

import java.util.Collection;
import java.util.Iterator;

/**
 * 作业: 自己实现 java.lang.Collection 接口中除了 iterator 和  toArray(T[] a) 之外的其它方法
 */
public class Container implements Collection<Object> {

	@Override
	public int size() {
		return 0;
	}

	@Override
	public boolean isEmpty() {
		return size()==0;
	}

	@Override
	public boolean contains(Object o) {
		Iterator<E> it = iterator();
        if (o==null) {
            while (it.hasNext())
                if (it.next()==null)
                    return true;
        } else {
            while (it.hasNext())
                if (o.equals(it.next()))
                    return true;
        }
		return false;
	}

	@Override
	public Object[] toArray() {
		Object[] r = new Object[size()];
        Iterator<E> it = iterator();
        for (int i = 0; i < r.length; i++) {
            if (! it.hasNext()) 
                return Arrays.copyOf(r, i);
            r[i] = it.next();
        }
        return it.hasNext() ? finishToArray(r, it) : r;
	}

	@Override
	public boolean add(Object e) {
		throw new UnsupportedOperationException();
	}

	@Override
	public boolean remove(Object o) {
		Iterator<E> it = iterator();
        if (o==null) {
            while (it.hasNext()) {
                if (it.next()==null) {
                    it.remove();
                    return true;
                }
            }
        } else {
            while (it.hasNext()) {
                if (o.equals(it.next())) {
                    it.remove();
                    return true;
                }
            }
        }
		return false;
	}

	@Override
	public void clear() {
		Iterator<E> it = iterator();
        while (it.hasNext()) {
            it.next();
            it.remove();
        }
	}
	
	@Override
	public boolean containsAll(Collection<?> c) {
		return false;
	}

	@Override
	public boolean addAll(Collection<? extends Object> c) {
		return false;
	}

	@Override
	public boolean removeAll(Collection<?> c) {
		return false;
	}

	@Override
	public boolean retainAll(Collection<?> c) {
		return false;
	}
	
	@Override
	public Iterator<Object> iterator() { // 【不去实现】
		return null;
	}
	
	@Override
	public <T> T[] toArray(T[] a) { // 【不去实现】
		return null;
	}

}
